import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3
import com.RspInterface 1.0
import com.AlmListModel 1.0
import com.ComboData 1.0
import "public.js" as Public


//批量强平
Item {
    id: batchForceCust
    property var tabName
    property var branchID
    property AlmListModel checkListModel
    property ComboData branchModel: g_MainQuo.getMyBranchs()
    property bool bInit: false
    property var custList: []
    signal freshData
    //参数row为-1时代表全部
    signal checkRowChange(int row, bool bCheck)

    //onCheckRowChange: checkListModel.setCheck(row, bCheck)
    onCheckRowChange: {
        console.log("root signal onCheckRowChange:" + row + " bcheck:" + bCheck)
        if (row >= 0) {
            //单个勾选的处理
            checkListModel.get(row).read_send = bCheck
        }
    }

    onBranchIDChanged: {
        if (branchID !== null) {
            var branch = "[" + branchID + "]" + g_MainQuo.getBranchName(
                        branchID)
            console.log("onBranchIDChanged " + branch)
            cmbBranch.currentIndex = cmbBranch.find(branch)
        }
        freshData()
    }
    ColumnLayout {
        anchors.fill: parent
        RowLayout {
            anchors.left: parent.left
            anchors.leftMargin: 10
            anchors.top: parent.top
            anchors.topMargin: 5
            anchors.right: parent.right
            anchors.rightMargin: 10
            Layout.preferredHeight: 180
            TabView {
                id: custInfo
                anchors.left: parent.left
                //                anchors.leftMargin: 10
                anchors.top: parent.top
                anchors.topMargin: 5
                anchors.right: parent.right
                anchors.rightMargin: 60
                anchors.bottom: parent.bottom
                anchors.bottomMargin: 3
                //                anchors.bottomMargin: 5
                Tab {
                    title: "当前强平客户"
                    CheckListFrame {
                        id: forceCustTab
                        tablelistName: "RiskCust2"
                        Connections {
                            target: batchForceCust
                            onFreshData: {
                                //                tableList.model
                                checkListModel = null
                                checkListModel = g_MainQuo.getForceCustModel(
                                            parseInt(topNum.currentText),
                                            "#belong=1#branch_id=" + branchID)
                            }
                        }

                        onCheckRowChange: {
                            console.log("onCheckRowChange:" + row + " bcheck:" + bCheck)
                            if (row >= 0) {
                                //单个勾选的处理
                                checkListModel.setCheck(row, bCheck)
                                checkListModel.resetModel()
                            }
                        }
                    }
                }
                Tab {
                    title: "所选客户未全部成交的平仓单"
                    PartMatchCovOrder {
                        have_cust: true
                    }
                }
            }
            ColumnLayout {
                anchors.top: parent.top
                anchors.left: custInfo.right
                //                anchors.leftMargin: 10
                anchors.right: parent.right
                //                anchors.rightMargin: 10
                anchors.bottom: parent.bottom
                spacing: 30
                CheckBox {
                    anchors.top: parent.top
                    anchors.topMargin: 60
                    anchors.right: parent.right
                    anchors.rightMargin: 10
                    Layout.alignment: Qt.AlignHCenter
                    text: qsTr("全选")
                    visible: custInfo.currentIndex === 0
                    onCheckedChanged: {
                        //                        console.log("onCheckedChanged:" + checked)
                        for (var i = 0; i < checkListModel.rowCount(); i++) {
                            checkListModel.setCheck(i, checked)
                        }
                        checkListModel.resetModel()
                        checkRowChange(-1, checked)
                    }
                }

                Button {
                    id: qryBtn
                    anchors.bottom: parent.bottom
                    anchors.bottomMargin: 50
                    anchors.right: parent.right
                    anchors.rightMargin: 5
                    Layout.preferredWidth: 50
                    Layout.alignment: Qt.AlignVCenter
                    text: "刷新"
                    onClicked: {
                        freshData()
                    }
                }
            }
        }
        GroupBox {
            id: forceOrderGroup
            Layout.fillHeight: true
            anchors.left: parent.left
            anchors.leftMargin: 10
            anchors.right: parent.right
            anchors.rightMargin: 10
            ColumnLayout {
                anchors.fill: parent
                RowLayout {
                    anchors.left: parent.left
                    anchors.leftMargin: 10
                    anchors.right: parent.right
                    anchors.rightMargin: 10
                    anchors.top: parent.top

                    Text {
                        text: "价格模式"
                    }
                    ComboBox {
                        id: cmbPriceModel
                        model: ListModel {
                            ListElement {
                                text: "停板价"
                                value: 1
                            }
                            ListElement {
                                text: "限价"
                                value: 2
                            }
                            ListElement {
                                text: "市价"
                                value: 3
                            }
                        }
                    }
                    Item {
                        Layout.fillWidth: true
                    }
                    Button {
                        text: "生成强平单"
                        onClicked: {
                            var req = "#oper_flag=1#risk_target=0#fc_mode="
                                    + cmbPriceModel.model.get(
                                        cmbPriceModel.currentIndex).value
                            var batchNo = Public.createID(5)
                            req += "#gen_condition="
                            console.log("click 生成强平单")
                            var createList = []
                            for (var i = 0; i < checkListModel.rowCount(
                                     ); ++i) {
                                var acctNo = checkListModel.getCellText(i, 0)
                                if (checkListModel.getCheck(i)) {
                                    req += acctNo + "｜"
                                    req += batchNo + "｜0｜∧"
                                    createList.push(acctNo)
                                }
                            }
                            console.log("createList size " + createList.length)
                            if (createList.length == 0) {
                                tipInput.text = "没有勾选风险客户"
                                tipInput.open()
                                return
                            }

                            custList = createList
                            var rsp = g_MainQuo.createBatchForceOrder(req)
                            var almName = "alm_result"
                            for (var k = 0; k < rsp.getAlmSize(almName); ++k) {
                                orderMgr.fOrderModel.append({
                                                                read_send: true,
                                                                AcctNo: rsp.getAlmString(
                                                                            almName,
                                                                            k,
                                                                            0),
                                                                create_id: "",
                                                                prod_code: rsp.getAlmString(
                                                                               almName, k, 2),
                                                                sale_type: rsp.getAlmString(
                                                                               almName, k, 3),
                                                                price: rsp.getAlmString(
                                                                           almName,
                                                                           k,
                                                                           4),
                                                                order_state: "未发送",
                                                                remain_amount: "",
                                                                order_id: rsp.getAlmString(
                                                                              almName, k, 1),
                                                                local_order_no: "",
                                                                sys_no: "",
                                                                info: "",
                                                                acct_no: acctNo,
                                                                amount: rsp.getAlmString(
                                                                            almName,
                                                                            k,
                                                                            5)
                                                            })
                            }
                            orderMgr.checkRowChange(-2, true)
                        }
                    }
                    Item {
                        Layout.preferredWidth: 10
                    }
                }

                ForceOrderMgr {
                    id: orderMgr
                    anchors.bottom: parent.bottom
                    anchors.left: parent.left
                    anchors.right: parent.right
                    anchors.rightMargin: 5
                    anchors.top: parent.top
                    anchors.topMargin: 30
                    Layout.fillHeight: true
                    have_cust: true

                    onCheckRowChange: {
                        console.log("onCheckRowChange:" + row + " bcheck:" + bCheck)
                        if (row >= 0) {
                            //单个勾选的处理
                            fOrderModel.get(row).read_send = bCheck
                            tryCloseAcct(fOrderModel.get(row).AcctNo)
                        } else if (!bCheck) {
                            tryCloseResultModel.clear()
                            return
                            //没有勾选
                        } else {
                            for (var i = 0; i < custList.length; i++)
                                tryCloseAcct(custList[i])
                        }
                    }
                }
            }
        }

        GroupBox {
            anchors.left: parent.left
            anchors.leftMargin: 10
            anchors.right: parent.right
            anchors.rightMargin: 10
            title: "预计参考结果"

            TableView {
                id: expect
                anchors.top: parent.top
                anchors.bottom: parent.bottom
                anchors.left: parent.left
                anchors.leftMargin: 5
                anchors.right: parent.right
                anchors.rightMargin: 5

                model: tryCloseResultModel
                TableViewColumn {
                    title: qsTr("客户号")
                    role: "AcctNo"
                    resizable: true
                    width: expect.width * 0.1
                    horizontalAlignment: Text.AlignLeft
                }

                TableViewColumn {
                    title: qsTr("风控可用")
                    role: "curr_bal"
                    resizable: true
                    width: expect.width * 0.12
                    horizontalAlignment: Text.AlignRight
                }

                TableViewColumn {
                    title: qsTr("交易所保证金")
                    role: "margin_exch"
                    resizable: true
                    width: expect.width * 0.12
                    horizontalAlignment: Text.AlignRight
                }
                TableViewColumn {
                    title: qsTr("会员保证金")
                    role: "margin_mem"
                    resizable: true
                    width: expect.width * 0.1
                    horizontalAlignment: Text.AlignRight
                }
                TableViewColumn {
                    title: qsTr("总保证金")
                    role: "margin_total"
                    resizable: true
                    width: expect.width * 0.1
                    horizontalAlignment: Text.AlignRight
                }
                TableViewColumn {
                    title: qsTr("浮动盈亏")
                    role: "float_surplus"
                    resizable: true
                    width: expect.width * 0.1
                    horizontalAlignment: Text.AlignRight
                }
                TableViewColumn {
                    title: qsTr("风险度1")
                    role: "risk_degree1"
                    resizable: true
                    width: expect.width * 0.1
                    horizontalAlignment: Text.AlignRight
                }
                TableViewColumn {
                    title: qsTr("风险度2")
                    role: "risk_degree2"
                    resizable: true
                    width: expect.width * 0.08
                    horizontalAlignment: Text.AlignRight
                }
                TableViewColumn {
                    title: qsTr("风险等级")
                    role: "risk_grade"
                    resizable: true
                    width: expect.width * 0.08
                    horizontalAlignment: Text.AlignLeft
                }
                TableViewColumn {
                    title: qsTr("仍需追保金额")
                    role: "call_debt"
                    resizable: true
                    width: expect.width * 0.1
                    horizontalAlignment: Text.AlignRight
                }
            }
        }

        RowLayout {
            anchors.left: parent.left
            anchors.leftMargin: 10
            anchors.right: parent.right
            anchors.rightMargin: 10
            Layout.preferredHeight: 40
            spacing: 20

            Text {
                text: "代理商："
                anchors.left: parent.left
                anchors.leftMargin: 10
            }
            ComboBox {
                id: cmbBranch
                model: branchModel
                Layout.preferredWidth: 240

                onCurrentIndexChanged: {
                    if (bInit) {
                        branchID = model.get(cmbBranch.currentIndex)
                        console.log("branchID:" + branchID)
                    }
                }

                Component.onCompleted: {
                    bInit = true
                }
            }
            Text {
                text: qsTr("显示前")
            }
            ComboBox {
                id: topNum
                Layout.preferredWidth: 55
                editable: true
                validator: RegExpValidator {
                    regExp: /\d{1,6}/
                }
                model: [10, 20, 30, 50]
            }
            Text {
                text: qsTr("位")
            }
            Item {
                Layout.fillWidth: true
            }
            //            Button {
            //                text: "关闭"
            //                anchors.right: parent.right
            //                anchors.rightMargin: 25
            //                onClicked: closeTab(tabName)
            //            }
            //            Item {
            //                Layout.preferredWidth: 25 //fillWidth把最后一个挤出去的bug补救
            //            }
        }
    }
    Button {
        text: "关闭"
        anchors.right: parent.right
        anchors.rightMargin: 25
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 10
        onClicked: closeTab(tabName)
    }
    ListModel {
        id: covOrderModel //平仓报单
    }

    ListModel {
        id: tryCloseResultModel //平仓试算结果
    }

    function tryCloseAcct(acctNo) {
        //平仓试算
        console.log("tryCloseAcct " + acctNo)
        var close_para = ""
        for (var k = 0; k < orderMgr.fOrderModel.count; k++) {
            if (!orderMgr.fOrderModel.get(k).read_send
                    || acctNo != orderMgr.fOrderModel.get(k).AcctNo)
                continue

            close_para += orderMgr.fOrderModel.get(k).prod_code
            close_para += "｜"
            var bsText = orderMgr.fOrderModel.get(k).sale_type
            if (bsText.indexOf("买") >= 0)
                close_para += "b"
            else
                close_para += "s"
            close_para += "｜"
            close_para += orderMgr.fOrderModel.get(k).price
            close_para += "｜"
            close_para += orderMgr.fOrderModel.get(k).amount
            close_para += "｜∧"
        }

        var refRow = -1
        for (var i = 0; i < tryCloseResultModel.count; ++i) {
            if (tryCloseResultModel.get(i).AcctNo == acctNo)
                refRow = i
        }

        if (close_para.length > 0) {
            var tryCalcRisk = g_MainQuo.tryCalcRiskInfo(acctNo, close_para)
            if (refRow >= 0) {
                tryCloseResultModel.get(refRow).curr_bal = tryCalcRisk.get(
                            "curr_bal")
                tryCloseResultModel.get(refRow).margin_exch = tryCalcRisk.get(
                            "margin_exch")
                tryCloseResultModel.get(refRow).margin_mem = tryCalcRisk.get(
                            "margin_mem")
                tryCloseResultModel.get(refRow).margin_total = tryCalcRisk.get(
                            "margin_total")
                tryCloseResultModel.get(refRow).float_surplus = tryCalcRisk.get(
                            "float_surplus")
                tryCloseResultModel.get(refRow).risk_degree1 = tryCalcRisk.get(
                            "risk_degree1")
                tryCloseResultModel.get(refRow).risk_degree2 = tryCalcRisk.get(
                            "risk_degree2")
                tryCloseResultModel.get(refRow).risk_grade = tryCalcRisk.get(
                            "risk_grade")
                tryCloseResultModel.get(refRow).call_debt = tryCalcRisk.get(
                            "call_debt")
            } else {
                tryCloseResultModel.append({
                                               AcctNo: acctNo,
                                               curr_bal: tryCalcRisk.get(
                                                             "curr_bal"),
                                               margin_exch: tryCalcRisk.get(
                                                                "margin_exch"),
                                               margin_mem: tryCalcRisk.get(
                                                               "margin_mem"),
                                               margin_total: tryCalcRisk.get(
                                                                 "margin_total"),
                                               float_surplus: tryCalcRisk.get(
                                                                  "float_surplus"),
                                               risk_degree1: tryCalcRisk.get(
                                                                 "risk_degree1"),
                                               risk_degree2: tryCalcRisk.get(
                                                                 "risk_degree2"),
                                               risk_grade: tryCalcRisk.get(
                                                               "risk_grade"),
                                               call_debt: tryCalcRisk.get(
                                                              "call_debt")
                                           })
            }
        } else if (refRow >= 0)
            tryCloseResultModel.remove(refRow)
    }
}
